package com.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.common.contant.RestResponse;
import com.common.exception.TaoException;
import com.common.exception.TaoExceptionEnum;
import com.common.utils.BeanHelper;
import com.common.vo.PageResult;


import com.dao.mapper.BrandMapper;
import com.dao.mapper.CategoryMapper;
import com.dto.BrandDTO;
import com.dto.CategoryDTO;
import com.entity.Brand;
import com.entity.Category;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.service.BrandService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeoutException;

/**
 * @Author: sijunqiang
 * @Date: 2020/5/18 20:41
 * @Description: 品牌查询的业务层
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))

public class BrandServiceImpl implements BrandService {

    private final BrandMapper brandMapper;


    private final CategoryMapper categoryMapper;

    @Override
    public PageResult<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key, String sortBy, Boolean desc) {

        //开始分页
        PageHelper.startPage(page, rows);

        // 添加过滤条件
        Example example = new Example(Brand.class);
        if (StringUtils.isNoneBlank(sortBy)) {
            // 根据name 模糊查询 且根据letter 精确查询
            example.createCriteria().orLike("name", "%" + key + "%").orEqualTo("letter", key.toUpperCase());
        }

        // 排序
        if (StringUtils.isNoneBlank(sortBy)) {
            String orderByClause = sortBy + (desc ? " DESC" : " ASC");
            example.setOrderByClause(orderByClause);
        }

        // 查询
        List<Brand> brands = brandMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(brands)) {
            throw new TaoException(TaoExceptionEnum.BRAND_NOT_FOUND);
        }

        // 解析分页结果
        PageInfo<Brand> brandPageInfo = new PageInfo<>(brands);
        // 转换brandDTO
        List<BrandDTO> brandDTOList = BeanHelper.copyWithCollection(brands, BrandDTO.class);
        //返回结果
        PageResult<BrandDTO> brandDTOPageResult = new PageResult<>(brandPageInfo.getTotal(), brandDTOList);
        return brandDTOPageResult;
    }


    /**
     * 保存品牌
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBrand(BrandDTO brandDTO, List<Long> cids) {
        // 新增品牌
        Brand brand = BeanHelper.copyProperties(brandDTO, Brand.class);
        brand.setId(null);
        int count = brandMapper.insertSelective(brand);
        if (count != 1) throw new TaoException(TaoExceptionEnum.INSERT_OPERATION_FAIL);
        // 新增品牌和分类中间表
        count = brandMapper.insertCategoryBrand(brand.getId(), cids);
        if (count != cids.size()) throw new TaoException(TaoExceptionEnum.INSERT_OPERATION_FAIL);
    }

    /**
     * 根据品牌的id 查询商品类目信息
     *
     * @param brandId 品牌的id
     * @return
     */

    @Override
    public RestResponse queryByBrandId(Long brandId) {
        // 根据品牌id 查询分类集合
        List<Category> categoryList = categoryMapper.queryByBrandId(brandId);
        if (CollectionUtils.isEmpty(categoryList)) return RestResponse.error(TaoExceptionEnum.CATEGORY_NOT_FOUND);
        List<CategoryDTO> categoryDTOS = BeanHelper.copyWithCollection(categoryList, CategoryDTO.class);
        log.info("<<<<<结束：根据品牌的id：[{}] 查询到的类目的集合信息：[{}]", brandId, JSONObject.toJSONString(categoryDTOS));
        return RestResponse.success(categoryDTOS);
    }


    /**
     * 根据品牌的id 查询品牌的信息
     *
     * @return
     */
    public BrandDTO queryById(Long id) {
        // 查询
        Optional<Brand> optional = Optional.ofNullable(brandMapper.selectByPrimaryKey(id));
        if (!optional.isPresent()) throw new TaoException(TaoExceptionEnum.BRAND_NOT_FOUND);
        Brand brand = optional.get();
        return BeanHelper.copyProperties(brand, BrandDTO.class);
    }


    /**
     * 根据品牌的id集合: 查询出品牌的信息集合
     */
    public List<BrandDTO> queryByIds(List<Long> brandIdList) {
        //查询数据
        Optional<List<Brand>> optional = Optional.ofNullable(brandMapper.selectByIdList(brandIdList));
        if (!optional.isPresent()) throw new TaoException(TaoExceptionEnum.BRAND_NOT_FOUND);
        //转换数据
        List<Brand> brands = optional.get();
        return BeanHelper.copyWithCollection(brands, BrandDTO.class);
    }



//    public List<BrandDTO> queryByCategory(Long categoryId) {
//        List<Brand> list = brandMapper.queryBrandByCategory(categoryId);
//        if (CollectionUtils.isEmpty(list)) {
//            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
//        }
//        return BeanHelper.copyWithCollection(list, BrandDTO.class);
//    }

}
